package cn.lena.idle.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import cn.lena.idle.pojo.Catagory;
import cn.lena.idle.pojo.DTO.CurrentCatagory;
import cn.lena.idle.pojo.User;
import cn.lena.idle.util.CurrencySQL;

/**
 * @author lena
 * @date 2021/6/10
 */
public class CatagoryDbHelper extends SQLiteOpenHelper {

    // 定义数据库表名
    public static final String DB_NAME = "tb_catagory";
    // 创建用户信息表
    private static final String CREATE_USER_DB = "create table "+DB_NAME+" (" +
            "id integer primary key autoincrement," +
            "name varchar(20))";
    // 默认分类
    private static final String DEFAULT_DATA ="insert into tb_catagory(name) "+
            "values('书籍'),('学习用品'),('电子产品'),('服饰'),('生活用品'),('化妆品'),('其他')";


    public CatagoryDbHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    /**
     * 根据分类id查询分类名称
     */
    public String getById(Integer id){
        SQLiteDatabase db=this.getWritableDatabase();
        String sql="select name from tb_catagory where id = ? ";
        Cursor cursor=db.rawQuery(sql,new String[]{id.toString()});
        if(cursor.moveToNext()){
            return cursor.getString(0);
        }
        return "";
    }

    /**
     * 查询所有分类 t
     * @return
     */
    public List<Catagory> getAll(){
        // 查询是否有记录，如果查询过不再进行查询。
        if(CurrentCatagory.CATAGORY_LIST != null){
            return CurrentCatagory.CATAGORY_LIST;
        }
        List<Catagory> catagories=new ArrayList<>();
        SQLiteDatabase db=this.getWritableDatabase();
        Cursor cursor=db.rawQuery("select * from "+DB_NAME,null);
        while(cursor.moveToNext()){
            catagories.add(new Catagory(cursor.getInt(0),cursor.getString(1)));
        }
        // 添加到类变量中 下次不会重复查询
        CurrentCatagory.CATAGORY_LIST=catagories;

        return catagories;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_USER_DB);
        db.execSQL(DEFAULT_DATA);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 销毁
        db.execSQL(CurrencySQL.DROP_SQL + DB_NAME);
        // 创建
        db.execSQL(CREATE_USER_DB);
        db.execSQL(DEFAULT_DATA);
    }


}
